//
//  ConfigVcPresent.swift
//  SunxianhuaTestApp
//
//  Created by abc on 2021/10/12.
//

import Foundation
import HandyJSON

protocol ConfigVcPresentDelegate :AnyObject{
    func reloadView()
}

class  ConfigVcPresent{
    
    var listModel :SearchKeyListModel!
    weak var delegate :ConfigVcPresentDelegate?
    var searchKey :String = ""
    init(any :ConfigVcPresentDelegate) {
        self.delegate = any
        
        self.listModel = SearchKeyListModel.init()
        TaskQueue.init().addOperation {[weak self] in
            self?.getAllSearchRecodes()
            self?.delegate?.reloadView()
        }
    }

    private func getAllSearchRecodes(){
        guard let json = CacheDataTool.getValue(ofKey: AppConfiguration.searchJsonKey) as? String,let list = SearchKeyListModel.deserialize(from: json) else {
            return
        }
        list.handleData()
        self.listModel = list
    }
    
    
    func addRecode(model :SearchKeyModel){
        
        self.listModel.searchKeyModelArray.append(model)
        self.delegate?.reloadView()
        CacheDataTool.save(value: self.listModel?.toJSONString(), toKey: AppConfiguration.searchJsonKey)
    }
    
    
    func deleteRecode(index :Int){
        
        self.listModel.searchKeyModelArray.remove(at: index)
        self.delegate?.reloadView()
        CacheDataTool.save(value: self.listModel?.toJSONString(), toKey: AppConfiguration.searchJsonKey)
    }
    
    
}
